//
//  RegisterViewController.m
//  Restaurant
//
//  Created by wanghuan on 15/4/20.
//  Copyright (c) 2015年 wanghuan. All rights reserved.
//

#import "RegisterViewController.h"

@interface RegisterViewController ()

@end

@implementation RegisterViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    self.view.backgroundColor = AppBackGroundColor;
    
    _AFmanager = [AFHTTPRequestOperationManager manager];
    
    _AFmanager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/json",@"text/html", nil];
    self.verifyText.delegate = self;
    self.passwordText.delegate = self;
    self.phoneNumText.delegate = self;
    self.verifyText.keyboardType = UIKeyboardTypeNumberPad;
    self.passwordText.keyboardType = UIKeyboardTypeDefault;
    self.passwordText.secureTextEntry = YES;
    self.phoneNumText.keyboardType = UIKeyboardTypeNumberPad;
    [self.verifyBtn setTitle:NSLocalizedString(@"获取验证码", nil) forState:UIControlStateNormal];
    
}

#pragma mark - textFiled未激活状态

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {

    [self.view endEditing:YES];

}

#pragma mark - UITextFieldDelegate

//当文本框输入结束的时候，开始验证验证码的正确性
- (void)textFieldDidEndEditing:(UITextField *)textField {

    
    
    

}

- (void)paste:(id)sender {

    UIPasteboard *pboard = [UIPasteboard generalPasteboard];
    
    if (pboard.string.length > 11) {
        self.phoneNumText.text = [pboard.string substringToIndex:11];
        
    }
}


- (BOOL)canPerformAction:(SEL)action withSender:(id)sender {

//    if (action == @selector(paste:)) {
//        return YES;
//    }
//
    
    if (action ==@selector(copy:)){
        
        return NO;
    }
    else if (action ==@selector(paste:)){
        return YES;
    }
    else if (action ==@selector(cut:)){
        return YES;
    }
    else if(action ==@selector(select:)){
        return NO;
    }
    else if (action ==@selector(delete:)){
        return NO;
    }
    return NO;
    
    return NO;

}

//限制文本框的字符个数
//文本框的文本是否允许被修改
-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    if (textField == self.verifyText) {
        if (range.location > 3) {
            return NO;
        }
        
        return YES;
    }
    
    if (textField == self.passwordText) {
        if (range.location > 13) {
            return NO;
        }
        
        return YES;
    }
    
    if (range.location > 10) {
        
        textField.text = @"";
        
        return NO;
    }
    
    return YES;
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

- (IBAction)verifyClick:(UIButton *)sender {
  
    sender.selected = !sender.selected;
    
    [self verifySender:sender];
    
}

- (void)verifySender:(UIButton *)sender {

    
    [_timer invalidate];
    //改变文本输入框的编辑状态
    self.phoneNumText.enabled = NO;
    self.phoneNumText.enabled = YES;
    

    if (!self.phoneNumText.text.length) {
        UIAlertView *alter = [[UIAlertView alloc]initWithTitle:@"提示" message:NSLocalizedString(@"手机号不能为空", nil) delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        
        [alter show];
    } else {
        
        if (![verifyPassAndPhone checkPhoneNumber:self.phoneNumText.text]) {
            //手机号码不正确
            UIAlertView* alert=[[UIAlertView alloc] initWithTitle:NSLocalizedString(@"提示", nil)
                                                          message:NSLocalizedString(@"手机号码不正确", nil)
                                                         delegate:self
                                                cancelButtonTitle:NSLocalizedString(@"确定", nil)
                                                otherButtonTitles:nil, nil];
            [alert show];
            
            return;
        }
        if (!sender.selected) {
            [self.verifyBtn setTitle:@"获取验证码" forState:UIControlStateNormal];
            
            return;
        }
        
        
        //默认是中国
        [SMS_SDK getVerificationCodeBySMSWithPhone:self.phoneNumText.text zone:@"86" result:^(SMS_SDKError *error) {
            
            if (error) {
                UIAlertView *alter = [[UIAlertView alloc]initWithTitle:@"提示" message:[NSString stringWithFormat:@"状态码：%zi,错误描述：%@",error.errorCode,error.errorDescription] delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
                
                [alter show];
            }
            
        }];
        
        time = 59;
        _timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timer) userInfo:nil repeats:YES];
        
        NSLog(@"%@",self.phoneNumText.text);

        
        
    }


}


- (void)timer {
    
   
    [self.verifyBtn setTitle:[NSString stringWithFormat:@"%d's重新获取",time] forState:UIControlStateNormal];
        
    
    
    if(time == 1) {
    
        [_timer invalidate];
        
        [self.verifyBtn setTitle:@"重新获取" forState:UIControlStateNormal];
        
        [self verifyClick:self.verifyBtn];
        
        return;
    
    }
    
    time--;
    
    
    
}

#pragma mark - MD5加密 

- (NSString *)MD5:(NSString *)sourceString {

    const char *cStr = [sourceString UTF8String];
    
    unsigned char digest[CC_MD5_DIGEST_LENGTH];

    CC_MD5(cStr, (unsigned)strlen(cStr), digest);
    
    NSMutableString *result = [NSMutableString stringWithCapacity:CC_MD5_DIGEST_LENGTH*2];

    for (int i = 0; i < CC_MD5_DIGEST_LENGTH; i++) {
        [result appendFormat:@"%02x",digest[i]];
        
    }
    
    return  result;
}

- (IBAction)registerClick:(UIButton *)sender {
    
    [self.view endEditing:YES];

    if (_phoneNumText.text.length) {
        
        if (_verifyText.text.length) {
            
            if (_passwordText.text.length) {
                
                //验证手机号是否正确
                if (![verifyPassAndPhone checkPhoneNumber:self.phoneNumText.text]) {
                    
                    UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"手机号错误" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
                    
                    [alert show];
                    
                    self.verifyText.text = @"";
                    self.passwordText.text = @"";
                    self.phoneNumText.text = @"";
                    
                    
                } else {
                    
                    //验证验证码是否正确
                    if (self.verifyText.text.length != 4) {
                        
                        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"验证码错误" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
                        
                        [alert show];
                        
                    } else {
                        
                        //验证密码是否正确
                        [self verifyPassWord];
                        
                    }
        
                }
                
            } else {
            
                UIAlertView *alterView = [[UIAlertView alloc]initWithTitle:NSLocalizedString(@"提示", nil) message:NSLocalizedString(@"密码不能为空", nil) delegate:self cancelButtonTitle:NSLocalizedString(@"确定", nil) otherButtonTitles:nil, nil];
                
                [alterView show];
                
                self.verifyText.text = @"";
                self.passwordText.text = @"";
            
            }
            
        } else {
        
            UIAlertView *alterView = [[UIAlertView alloc]initWithTitle:NSLocalizedString(@"提示", nil) message:NSLocalizedString(@"验证码不能为空", nil) delegate:self cancelButtonTitle:NSLocalizedString(@"确定", nil) otherButtonTitles:nil, nil];
            
            [alterView show];
            
        }
        
        
    } else {
    
        UIAlertView *alterView = [[UIAlertView alloc]initWithTitle:NSLocalizedString(@"提示", nil) message:NSLocalizedString(@"手机号不能为空", nil) delegate:self cancelButtonTitle:NSLocalizedString(@"确定", nil) otherButtonTitles:nil, nil];
        
        [alterView show];
    
    }
   

}




#pragma mark - 验证验证码

- (void)verifyPassWord {

    [SMS_SDK commitVerifyCode:self.verifyText.text result:^(enum SMS_ResponseState state) {
        
        if (1==state)
        {
            NSLog(@"验证成功");
            
            //密码密码格式
            if (![verifyPassAndPhone checkPassword:self.passwordText.text]) {
                
                UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"密码格式只能由数字或字母组成" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
                
                [alert show];
                
            } else {
                
                //立即注册
                [self registerClick];
                
            }
            
        } else if(0==state)
        {
            NSLog(@"验证失败");
            NSString* str=[NSString stringWithFormat:NSLocalizedString(@"验证失败", nil)];
            UIAlertView* alert=[[UIAlertView alloc] initWithTitle:NSLocalizedString(@"提示", nil)
                                                          message:str
                                                         delegate:self
                                                cancelButtonTitle:NSLocalizedString(@"确定", nil)
                                                otherButtonTitles:nil, nil];
            [alert show];
        }
        
        
    }];


}

#pragma mark - 立即注册

- (void)registerClick {

    //密码加密
    NSString *passwordStr = [self MD5:self.passwordText.text];
    
    _AFmanager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/json",@"text/html",@"application/json", nil];
    
    NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:self.phoneNumText.text,@"telephone",passwordStr,@"password", nil];
    
    [_AFmanager POST:registerUrl parameters:dict success:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        NSLog(@"responseObject=%@",responseObject);
        
        if ([[responseObject objectForKey:@"success"]boolValue]) {
            
            [self Login:passwordStr];
            
        } else {
            
            UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示" message:[responseObject objectForKey:@"code"] delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
            
            [alert show];
        }
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"注册失败" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        
        [alert show];
    }];


}

#pragma mark - 立即登录
- (void)Login:(NSString *)passwordStr{

    NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:self.phoneNumText.text,@"telephone",passwordStr,@"password", nil];
    
    [_AFmanager POST:LoginUrl parameters:dict success:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        NSLog(@"responseObject = %@",responseObject);
        
        //登陆成功
        if ([[responseObject objectForKey:@"success"]boolValue]) {
            
            NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
            
            [defaults setObject:[[responseObject objectForKey:@"obj"] objectForKey:usersId] forKey:usersId];
            
            [defaults setObject:[[responseObject objectForKey:@"obj"] objectForKey:Usertelephone] forKey:Usertelephone];
            
            [defaults setObject:[[responseObject objectForKey:@"obj"] objectForKey:Userpassword] forKey:Userpassword];
            
            [defaults synchronize];
            
            if (self.viewController) {
                
                 [self.navigationController popToViewController:self.viewController animated:YES];
                
            } else {
            
                [self.navigationController popViewControllerAnimated:YES];
            }
            
            
            
        } else {
            
            //登录失败
            UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示" message:[responseObject objectForKey:@"code"] delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
            
            [alert show];
        }
        
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"连接超时" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        
        [alert show];
        
    }];


}

- (IBAction)backClick:(UIButton *)sender {
    
    
    [self.navigationController popViewControllerAnimated:YES];
    
}
@end
